package com.amway.qy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.core.QyWechatBox;
import com.amway.qy.core.callback.QyAbstractCallbackHandlerImpl;
import com.amway.qy.core.config.QyWechatConfig;
import com.amway.qy.message.req.ReqTextMessage;
import com.amway.qy.message.resp.RespTextMessage;
import com.amway.qy.util.common.XmlUtils;

public class CoreServlet extends HttpServlet {

	private static final Logger logger = LoggerFactory.getLogger(CoreServlet.class);
	
	private static QyWechatBox box;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {
		super.init();
		String token = "y1u8KW7YbNugoGcgH7vfGOecid";
		String corpid = "wxe5d3826a4a0d5cf8";
		String corpsecret = "J8vogKw7OvF87y0kqVA0FUhBu4uABe4idldnTOlAtY2ksoD0zH1f2xVjXXFqqK5c";
		String sEncodingAESKey = "gkmym4ubGLvkjOx9aSyXhDmz5oWBCmr4TIPnqjsu9za";

		QyWechatConfig config = new QyWechatConfig();
		config.setToken(token);
		config.setCorpid(corpid);
		config.setCorpsecret(corpsecret);
		config.setsEncodingAESKey(sEncodingAESKey);

		box = QyWechatBox.initialize(config);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		String result = null;
		try {
			result = box.verifyURL(signature, timestamp, nonce, echostr);
			PrintWriter out = resp.getWriter();
			out.print(result);
			out.flush();
			out.close();
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 微信加密签名
		String msg_signature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");

		Map<String, String> postData;
		try {
			String postString = XmlUtils.convertStreamToString(request.getInputStream());
			String decryptXml = box.decryptMsg(msg_signature, timestamp, nonce, postString);

			postData = XmlUtils.parseXml(postString);

			Map<String, String> tmp = XmlUtils.parseXml(decryptXml);
			for (Entry<String, String> entry : tmp.entrySet()) {
				postData.put(entry.getKey(), entry.getValue());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		String respMessage = null;
		try {
			respMessage = box.processRequest(postData, new QyAbstractCallbackHandlerImpl() {

				@Override
				public String handleTextRequest(ReqTextMessage text) {

					logger.info("Received-->" + text);

					RespTextMessage ret = new RespTextMessage(text.getFromUserName(),box.getConfig().getCorpid(),"Hello world");

					logger.info("Before send-->" + ret);

					String xml = XmlUtils.convertTextMessageToXml(ret);

					logger.info("After convert-->" + xml);

					return xml;
				}

			});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		logger.info("response body->" + respMessage);

		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}
	
	public static void main(String[] args){
		for(int i = 0 ; i < 100; i++){
			String t = System.currentTimeMillis()+"";
			System.out.println(t +"-->" + t.length());
		}
	}
}
